package com.cssnj.portal.service.manage.modify;

import com.cssnj.portal.domain.func.GlGnEntity;
import com.cssnj.portal.domain.func.GlGnRepository;
import com.cssnj.portal.domain.manage.*;
import com.cssnj.portal.utils.PinYinUtils;
import com.cssnj.portal.utils.PortalUntil;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.exception.BaseException;
import io.predictech.framework.service.base.BaseService;
import io.predictech.framework.utility.PredictechUtil;
import io.predictech.framework.utility.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 功能变更申请
 *
 * @author Arthur
 * @version 1.0
 * @since 2018-9-18 13:49
 */
@Service
public class ModifyApplyService extends BaseService {

    @Autowired
    private YyGnJrRepository jrRepository;

    @Autowired
    private YyGnJrXqSmRepository xqSmRepository;

    @Autowired
    private YyGnJrJsSmRepository jsSmRepository;

    @Autowired
    private GlGnRepository glGnRepository;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Override
    protected JsonResponse invokingService(JsonRequest jsonRequest) throws SQLException, BaseException {
        return null;
    }

    /**
     * @description 根据功能ID 获取申请内容
     * @author Arthur
     * @since 2018-9-18 17:13
     **/
    public JsonResponse getApplyByFuncId(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();

        String funcId = jsonRequest.getReqData().get("funcId").toString();

        if (StringUtils.isNotEmpty(funcId)) {
            Optional<YyGnJrEntity> yyGnJrEntityOptional = jrRepository.findById(funcId);
            YyGnJrEntity yyGnJrEntity = yyGnJrEntityOptional.orElseGet(YyGnJrEntity::new);
            List<YyGnJrXqSmEntity> xqSmEntities = xqSmRepository.findByGnId(funcId);
            List<YyGnJrJsSmEntity> jrJsSmEntities = jsSmRepository.findByGnId(funcId);

            jsonResponse.getRepData().put("jrMap", yyGnJrEntity);
            jsonResponse.getRepData().put("xqList", xqSmEntities);
            jsonResponse.getRepData().put("jsList", jrJsSmEntities);
        } else {
            PortalUntil.logger().error("功能ID不可为空");
            jsonResponse.setCode("E9036");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
        }
        return jsonResponse;
    }

    /**
     * @description 应用变更申请
     * @author Arthur
     * @since 2018-9-19 15:11
     **/
    public JsonResponse establishModifyApply(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();

        PortalUntil.logger().debug("开始创建功能变更申请");

        String funcId = StringUtil.empty(jsonRequest.getReqData().get("funcId"));

        // 检查功能ID是否存在
        if (StringUtils.isEmpty(funcId)) {
            PortalUntil.logger().error("功能ID不可为空");
            jsonResponse.setCode("E9036");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
            return jsonResponse;
        }


        // 获取当前应用申请，功能主表，应用信息，需求，技术说明
        GlGnEntity glGnEntity = glGnRepository.findById(funcId).orElseGet(GlGnEntity::new);
        YyGnJrEntity jrEntity = jrRepository.findById(funcId).orElseGet(YyGnJrEntity::new);
        // 判断功能情况
        if (StringUtils.isEmpty(jrEntity.getYyid())) {
            PortalUntil.logger().error("错误的功能.无法获取功能对应应用");
            jsonResponse.setCode("E9036");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
            return jsonResponse;
        }
        Map<String, Object> jcXxMap = PredictechUtil
                .getCodeData("YY_JCXX")
                .stream()
                .filter(map -> jrEntity.getYyid().equals(map.get("YY_ID")))
                .findFirst()
                .orElseGet(HashMap::new);
        List<YyGnJrXqSmEntity> xqSmEntities = xqSmRepository.findByGnId(funcId);
        List<YyGnJrJsSmEntity> jrJsSmEntities = jsSmRepository.findByGnId(funcId);

        // 校验链接是否合规
        String href = jsonRequest.getReqData().get("funcHref").toString();
        if (jcXxMap.isEmpty() || !href.startsWith((String) jcXxMap.get("YY_GW"))) {
            PortalUntil.logger().error("功能链接与应用链接应在同一域内 -> yyHref : " + jcXxMap.get("YY_GW") + " funcHref : " + href);
            jsonResponse.setCode("W1097");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
            return jsonResponse;
        }

        // 简单校验结束
        // 删除被删除的文件
        // 遍历Map
        Map<String, Object> requestMap = jsonRequest.getReqData();
        for (String key : requestMap.keySet()) {
            if (key.startsWith("demandExplainFilePath")) {
                xqSmEntities.removeIf(entity ->
                        (entity.getFjlj().equals(requestMap.get(key)))
                                &&
                                (entity.getFjmc().equals(requestMap.get(key.replaceAll("Path", ""))))
                );
            } else if (key.startsWith("technologyExplainFilePath")) {
                jrJsSmEntities.removeIf(entity ->
                        (entity.getFjlj().equals(requestMap.get(key)))
                                &&
                                (entity.getFjmc().equals(requestMap.get(key.replaceAll("Path", ""))))
                );
            }
        }
        // 删除剩余的文件
        xqSmEntities.forEach(entity -> {
            PortalUntil.logger().debug("功能变更 -- 开始删除需求文件 -> name : " + entity.getFjmc() + "; path : " + entity.getFjlj());
            xqSmRepository.delete(entity);
            fastFileStorageClient.deleteFile(entity.getFjlj());
        });
        jrJsSmEntities.forEach(entity -> {
            PortalUntil.logger().debug("功能变更 -- 开始删除技术文件 -> name : " + entity.getFjmc() + "; path : " + entity.getFjlj());
            jsSmRepository.delete(entity);
            fastFileStorageClient.deleteFile(entity.getFjlj());
        });

        String gnMc = jsonRequest.getReqData().get("gnMc").toString();
        String funcExplain = jsonRequest.getReqData().get("funcExplain").toString();
        String demandExplain = StringUtil.castBase64ToStr(jsonRequest.getReqData().get("demandExplain").toString());
        String technologyExplain = StringUtil.castBase64ToStr(jsonRequest.getReqData().get("technologyExplain").toString());

        // 开始应用申请变更
        jrEntity.setGnMc(gnMc);
        jrEntity.setGnId(funcId);
        jrEntity.setGnms(funcExplain);
        jrEntity.setGnJc(PinYinUtils.getPinYinHeadChar(gnMc));
        jrEntity.setJssm(technologyExplain);
        jrEntity.setXqsm(demandExplain);
        jrEntity.setSjgnId(glGnEntity.getSjgnId());
        jrEntity.setHref(href);
        jrEntity.setStatus("01");
        jrEntity.setBeKjfs(glGnEntity.getBeKjfs());
        jrEntity.setXybj(glGnEntity.getXyBj());
        jrEntity.setKzBj(glGnEntity.getKzBj());
        jrEntity.setXsBj(glGnEntity.getXsBj());
        jrEntity.setXgsj(this.queryDao.getSystimestamp());

        jrRepository.save(jrEntity);

        PortalUntil.logger().debug("功能变更 -> 申请创建成功");

        return jsonResponse;
    }
}
